/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trumpet.core;

import javax.swing.DefaultListModel;
import trumpet.core.buddylist.CollectionAdapterXmlFile;

/**
 *
 * @author Artur
 */
public class UserCollection extends DefaultListModel {


    public UserCollection(User[] u) {
        for(int i = 0; i < u.length; i++) {
            this.addElement(u[i]);
        }
    }

    public UserCollection() {

       // this(testUsers);
        adapter = new CollectionAdapterXmlFile(filePath);
        this.users = adapter.getElements();

        for(int i = 0; i < this.users.length; i++) {
            super.addElement(this.users[i]);
        }

    }

    /**
     * @return the users
     */
    public User[] getUsers() {
        return users;
    }

    /**
     * @param users the users to set
     */
    public void setUsers(User[] users) {
        this.users = users;
    }
    public void addElement(User user) {
        if(user.hasId()) {
            super.setElementAt(user, user.getId() - 1);
            this.getAdapter().editElement(user);
        } else {
            super.addElement(user);
            user.setId(this.size() - 1);
            this.getAdapter().addElement(user);
        } 
    }

    @Override
    public void removeElementAt(int index) {
        super.remove(index);
        this.getAdapter().deleteElementAt(index);
    }

    public CollectionAdapterXmlFile getAdapter() {
        return this.adapter;
    }

    public User getByIp(String ipAddress)
    {
        for(int i = 0; i < this.getSize(); i++) {
            User usr = (User) this.getElementAt(i);
            if(usr.getIp().equals(ipAddress)) {
                return usr;
            }
        }

        return null;
    }

    private String filePath = "src/Data/BuddyList.xml";

    private User[] users;

    private CollectionAdapterXmlFile adapter;
}
